package com.strato.mvc.view.velocity.v1_0_0.resource;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

import com.strato.base.osgi.v1_0_0.BundleUtil;
import com.strato.mvc.api.v1_0_0.view.ViewName;
import com.strato.mvc.api.v1_0_0.view.ViewResolver;
import com.strato.mvc.view.velocity.v1_0_0.activator.Activator;

public class BundleResourceLoader extends ResourceLoader {

	@Override
	public long getLastModified(Resource resource) {
		ViewName viewName=ViewResolver.parseViewName(resource.getName());
		BundleContext bundleContext = Activator.getContext();
		Bundle bundle=BundleUtil.getBundle(viewName.getBundle(),bundleContext);
		if(bundle==null){
			return 0;
		}
		return bundle.getLastModified();
	}

	@Override
	public InputStream getResourceStream(String name) throws ResourceNotFoundException {
		ViewName viewName=ViewResolver.parseViewName(name);
		BundleContext bundleContext = Activator.getContext();
		Bundle bundle=BundleUtil.getBundle(viewName.getBundle(),bundleContext);
		if(bundle==null){
			return null;
		}
		String path=viewName.getPath();
		try {
			URL url = bundle.getResource(path+".vm");
			if(url==null){
				return null;
			}
			return url.openStream();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean isSourceModified(Resource name) {
		return false;
	}

	@Override
	public void init(ExtendedProperties properties) {
	}

}
